package com.situ.order.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.order.client.UserClient;
import com.situ.order.mapper.OrderMapper;
import com.situ.order.pojo.Order;
import com.situ.order.pojo.User;
import com.situ.order.service.IOrderService;
import com.situ.order.util.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserClient userClient;

    @Override
    public Order selectById(Long id) {
        Order order =  orderMapper.selectById(id);
        try {
            //使用RestTemplate发起http请求，访问user-service，查找用户信息
            //String url = "http://localhost:8081/user/" + order.getUserId();

            //String url = "http://userservice/user/" + order.getUserId();
            //JSONResult jsonResult = restTemplate.getForObject(url, JSONResult.class);

            JSONResult jsonResult = userClient.selectById(order.getUserId());

            //Jackson
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonStr = objectMapper.writeValueAsString(jsonResult.getData());

            User user = objectMapper.readValue(jsonStr, User.class);
            order.setUser(user);
            return order;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;

    }
}
